import math
import os

from PyQt5.QtCore import QTimer
from data.DataHandler import datahandler
from data.defines import *
from data.gisutils import cal_runway_distance, util_calc_ref_pos
from data.warnning_config import warnhandler
from gcs_views.LandPlotPad import LandPlotPad
from gcs_views.PosSendPad import PosSendPad
from gcs_views.RouteSetPad import RouteSetPad
from gcs_views.AirportSetPad import AirportSetPad
# from gcs_views.CurveLinePad import CurveLinePad
# from gcs_views.PosTransferPad import PosTransferPad
# from gcs_views.RemoteDataPad import RemoteDataPad
from gcs_views.ui_gcs_gui_1 import *
import logging

# import configparser

com_style1 = 'color: rgb(0, 0, 0);\nbackground-color: rgb(166, 166, 166);\nfont: 75 12pt "Noto Sans ' \
             'S Chinese Bold"; '

com_style2 = 'color: rgb(0, 0, 0);\nbackground-color: rgba(0, 200, 0,255);\nfont: 75 12pt "Noto Sans ' \
             'S Chinese Bold"; '
POINT_AT_BAT = 0.05  # 指示为蓄电池供电
POINT_AT_GENERATOR = 0.5  # 指示发电机供电
POINT_AT_GROUND = 0.95  # 指示地面电源供电

POINT_AT_BUSA = 0.05  # 指示为汇流条A
POINT_AT_BUSB = 0.5  # 指示汇流条B
POINT_AT_BUSC = 0.95  # 指示汇流条C

file_path_mac = os.getcwd() + '/'
file_path_win = os.getcwd() + '\\'


def online_route_upload_enable():
    cmd_send = datahandler.pre_send_request_cmd(0, COMMAND_CTRL_ROUTE_ON)
    datahandler.send_request(cmd_send)


def online_route_upload_disable():
    cmd_send = datahandler.pre_send_request_cmd(0, COMMAND_CTRL_ROUTE_OFF)
    datahandler.send_request(cmd_send)


def online_route_delete():
    # 发送在线航线删除命令
    cmd_send = datahandler.pre_send_request_cmd(0, COMMAND_CTRL_ROUTE_DEL)
    datahandler.send_request(cmd_send)


def route_upload(route_list: list, dot_num: int):
    print("TBD:航线装订")  # 开始航线装订 本地发出，外部接收


class GCSMapClass(Ui_GCSWindow1):

    def __init__(self):
        super(GCSMapClass, self).__init__()

        self.left_runway = 0
        self.RemoteDataPad = None
        self.PosTransferPad = None
        self.LandProfilePad = None
        self.CurveLinePad = None
        self.AirportSetPad = None
        self.RouteSetPad = None

        self.lon_deg_old = None
        self.lat_deg_old = None

        self.timer = QTimer()  # 创建窗口定时器，用于处理周期任务
        self.timer.timeout.connect(self.timer_process)
        self.timer.start(100)

    def timer_process(self):
        pass
        # print("timer_process called!")

    def setupGCSMapClass(self):
        """
        地图页面初始化
        :return:
        """
        # 地图控件初始化
        self.map_widget.interact_obj.sigFromWebGetMouseLonLat.connect(self.getMouseLonLat)

        # 电气系统控件初始化
        self.elec_system_indicator_init()

        # 高度剖面系统初始化（暂不实现）

        # 信号指示灯控件初始化

        # TODO:子页面弹窗按钮功能初始化
        self.AirportSetPad = AirportSetPad()
        self.AirportSetPad.rwy_sig_show_to_map.connect(self.show_rwy2map)
        self.AirportSetPad.rwy_sig_upload_takeoff_rwy.connect(self.upload_takeoff_rwy)
        self.AirportSetPad.rwy_sig_upload_landing_rwy.connect(self.upload_landing_rwy)
        self.AirportSetPad.rwy_sig_get_rwy.connect(self.send_get_rwy_cmd)  # 查询跑道参数
        self.AirportSetPad.rwy_sig_delete_rwy.connect(self.send_del_rwy_cmd)  # 删除跑道数据
        self.AirportSetPad.rwy2_sig_show_to_map.connect(self.show_second_rwy2map)
        self.AirportSetPad.taxi_route_sig_show2map.connect(self.map_widget.show_taxi_routes2map)
        self.AirportSetPad.taxiin_sig_upload_start.connect(
            lambda route_list, dot_num: datahandler.send_route_start(route_list, 1))
        self.AirportSetPad.taxiout_sig_upload_start.connect(
            lambda route_list, dot_num: datahandler.send_route_start(route_list, 2))
        self.AirportSetPad.taxiin_sig_get_config.connect(lambda: datahandler.request_route_start(1))
        self.AirportSetPad.taxiout_sig_get_config.connect(lambda: datahandler.request_route_start(2))
        datahandler.sig_taxiin_route_download_cmp.connect(
            lambda route_list: self.AirportSetPad.taxiin_sig_get_result.emit(route_list))
        datahandler.sig_taxiout_route_download_cmp.connect(
            lambda route_list: self.AirportSetPad.taxiout_sig_get_result.emit(route_list))

        self.RouteSetPad = RouteSetPad()
        self.RouteSetPad.online_sig_upload_start.connect(
            lambda route_list, dot_num: datahandler.send_route_start(route_list, 0))
        self.RouteSetPad.online_sig_show2map.connect(self.online_route_show2map)  # 将在线航线显示到地图 本地发出，外部接收
        self.RouteSetPad.online_sig_load_from_map.connect(self.online_route_load_from_map)  # 从地图加载在线航线信号，本地发出，外部接收
        self.RouteSetPad.online_sig_get_config.connect(
            lambda: datahandler.request_route_start())  # 发送航线查询命令 本地发出
        self.RouteSetPad.online_sig_delete_config.connect(online_route_delete)  # 发送在线航线删除命令
        self.RouteSetPad.online_sig_upload_enable.connect(online_route_upload_enable)
        self.RouteSetPad.online_sig_upload_disable.connect(online_route_upload_disable)
        datahandler.sig_online_route_download_cmp.connect(self.online_download_route_cmp)

        self.RouteSetPad.route_sig_upload_start.connect(route_upload)  # 开始航线装订 本地发出，外部接收
        self.RouteSetPad.route_sig_show2map.connect(self.route_show2map)  # 将航线显示到地图 本地发出，外部接收
        self.RouteSetPad.route_sig_load_from_map.connect(self.route_load_from_map)  # 从地图加载在航线信号，本地发出，外部接收
        self.RouteSetPad.route_sig_get_config.connect(self.route_getconfig)  # 发送航线查询命令 本地发出
        self.RouteSetPad.route_sig_delete_config.connect(self.route_delete)  # 发送航线删除命令
        datahandler.sig_route_download_cmp.connect(self.route_download_cmp)  # 航线查询成功提示

        # self.CurveLinePad = CurveLinePad()
        self.LandProfilePad = LandPlotPad()
        self.PosTransferPad = PosSendPad()
        # self.RemoteDataPad = RemoteDataPad()

        self.btn_airline_set.clicked.connect(self.airline_set)
        self.btn_AirportSet.clicked.connect(self.airport_set)
        self.btn_pos_transfer.clicked.connect(self.pos_transfer)
        # self.btn_remote_data.clicked.connect(self.remote_data)
        # self.btn_curve_line.clicked.connect(self.curve_line)
        self.btn_landing_profile.clicked.connect(self.landing_profile)
        self.btn_set_view_center.clicked.connect(self.map_widget.set_view_at_plane)
        self.btn_set_view_to_route.clicked.connect(self.map_widget.set_view_at_route)
        self.btn_web_reload.clicked.connect(self.map_widget.webview_reload)
        # 接收数据信号绑定处理函数
        datahandler.sig_RecvServoData.connect(self.servo_system_data_process)
        datahandler.sig_RecvFccSystmData.connect(self.fcc_system_data_process)
        datahandler.sig_RecvSensorINS.connect(self.sensor_mins_data_process)
        datahandler.sig_RecvSensorBINS.connect(self.sensor_bins_data_process)
        datahandler.sig_RecvSensorADC.connect(self.sensor_adc_data_process)
        datahandler.sig_RecvSensorRadar.connect(self.sensor_radar_data_process)
        datahandler.sig_RecvSensorGPS.connect(self.sensor_gps_data_process)
        datahandler.sig_RecvDataLink.connect(self.datalink_data_process)
        datahandler.sig_RecvElecSystem.connect(self.elec_system_data_process)
        datahandler.sig_RecvEngineSystem.connect(self.engine_system_data_process)
        datahandler.sig_RecvWarningSystem.connect(self.warnning_system_data_process)
        datahandler.sig_RecvCommandEcho.connect(self.command_echo_data_process)
        datahandler.sig_RecvEquipment.connect(self.equipment_data_process)

        datahandler.sig_pre_send_request.connect(self.pre_send_data_process)
        datahandler.sig_send_request.connect(self.send_data_process)
        datahandler.sig_request_echo.connect(self.request_echo_process)
        logging.info("主页面数据绑定完成")

        self.AirportSetPad.taxiin_route_sig_load_from_map.connect(self.taxiin_route_load_from_map)

    def taxiin_route_load_from_map(self):
        self.AirportSetPad.taxiin_route_sig_download_finished.emit(self.map_widget.taxi_route_list)
        #print('taxiin_route_load_from_map')
        #print(self.map_widget.taxi_route_list)

    def online_download_route_cmp(self, route_list: list):
        self.RouteSetPad.online_sig_download_finished.emit(route_list, len(route_list))

    def online_route_show2map(self, route_list: list, dot_num: int):
        # print(dot_num)
        self.map_widget.sig_show_route(route_list)

    def online_route_load_from_map(self):
        dot_num = len(self.map_widget.route_list)
        self.RouteSetPad.online_sig_load_finished.emit(self.map_widget.route_list, dot_num)

    def route_download_cmp(self, route_list: list):
        self.RouteSetPad.route_sig_load_finished.emit(route_list, len(route_list))

    def route_show2map(self, route_list: list, dot_num: int):
        self.map_widget.sig_show_route(route_list)

    def route_load_from_map(self):
        dot_num = len(self.map_widget.route_list)
        self.RouteSetPad.route_sig_download_finished.emit(self.map_widget.route_list, dot_num)

    def route_getconfig(self, line_idx: int):
        print("查询航线%d" % line_idx)
        # TODO:发送航线查询命令

    def route_delete(self, line_idx: int):
        print("删除航线%d" % line_idx)  # 发送航线删除命令
        # TODO:发送航线删除命令

    def send_get_rwy_cmd(self):
        print("send_get_rwy_cmd called")
        # TODO:发送查询跑道指令，等待查询结果并将结果回传到设置页面
        rwy_result = {
            "takeoff_rwy":
                {
                    "idx": 14,
                    "lon": 113.7432212,
                    "lat": 42.2701277,
                    "alt": 1282,
                    "psi": 134.84,
                    "len": 1200
                },
            "landing_rwy": {
                "idx": 32,
                "lon": 113.7535611,
                "lat": 42.2624918,
                "alt": 1285,
                "psi": 314.84,
                "len": 1200
            }
        }

        self.AirportSetPad.rwy_sig_get_config_result.emit(rwy_result)

    def send_del_rwy_cmd(self):
        print("send_del_rwy_cmd called")
        # TODO:根据命令返回结果决定是否触发删除查询框信号
        self.AirportSetPad.rwy_sig_get_delete_result.emit()

    def upload_takeoff_rwy(self, data):
        print(data)
        # TODO:通过遥调指令上传起飞跑道信息

    def upload_landing_rwy(self, data):
        print(data)
        # TODO:通过遥调指令上传着陆跑道信息

    def show_second_rwy2map(self, data):
        try:
            start_lon = data['start_lon']
            start_lat = data['start_lat']
            end_lon = data['end_lon']
            end_lat = data['end_lat']
            width = data['width']
            self.map_widget.show_second_runway_info(start_lon, start_lat, end_lon, end_lat, width)
        except Exception as err:
            logging.error(repr(err))

    def show_rwy2map(self, data):
        try:
            start_lon = data['start_lon']
            start_lat = data['start_lat']
            end_lon = data['end_lon']
            end_lat = data['end_lat']
            width = data['width']
            self.map_widget.show_runway_info(start_lon, start_lat, end_lon, end_lat, width)
        except Exception as err:
            logging.error(repr(err))

    def airline_set(self):
        self.RouteSetPad.show()
        self.RouteSetPad.raise_()

    def airport_set(self):
        self.AirportSetPad.show()
        self.AirportSetPad.raise_()

    def pos_transfer(self):
        self.PosTransferPad.show()
        self.PosTransferPad.raise_()

    # def remote_data(self):
    #     self.RemoteDataPad.show()
    #     self.RemoteDataPad.raise_()

    # def curve_line(self):
    #     self.CurveLinePad.show()
    #     self.CurveLinePad.raise_()

    def landing_profile(self):
        self.LandProfilePad.show()
        self.LandProfilePad.raise_()

    def elec_system_indicator_init(self):
        """
        电气系统示意图区域控件初始化
        :return:
        """
        self.line_power_source.start_y = POINT_AT_BAT
        self.line_power_source.end_y_list = []
        self.line_power_source.end_y_list.append(POINT_AT_BUSA)  # 指向汇流条A
        self.line_power_source.end_y_list.append(POINT_AT_BUSB)  # 指向汇流条B
        self.line_power_source.end_y_list.append(POINT_AT_BUSC)  # 指向汇流条C
        self.line_power_source.setStatus(WidgetLINE.LINE_ENABLE)
        self.line_sourceA.start_y = 0.526
        self.line_sourceA.end_y_list = []
        self.line_sourceA.end_y_list.append(0.0584)
        self.line_sourceA.end_y_list.append(0.23383)
        self.line_sourceA.end_y_list.append(0.40928)
        self.line_sourceA.end_y_list.append(0.58471)
        self.line_sourceA.end_y_list.append(0.76015)
        self.line_sourceA.end_y_list.append(0.9356)
        self.line_sourceA.setStatus(WidgetLINE.LINE_ENABLE)
        self.line_sourceB.start_y = 0.5
        self.line_sourceB.end_y_list = []
        self.line_sourceB.end_y_list.append(0.0709)
        self.line_sourceB.end_y_list.append(0.2837)
        self.line_sourceB.end_y_list.append(0.4964)
        self.line_sourceB.end_y_list.append(0.7092)
        self.line_sourceB.end_y_list.append(0.9220)
        self.line_sourceB.setStatus(WidgetLINE.LINE_ENABLE)
        self.line_sourceC.start_y = 0.468
        self.line_sourceC.end_y_list = []
        self.line_sourceC.end_y_list.append(0.0584)
        self.line_sourceC.end_y_list.append(0.23383)
        self.line_sourceC.end_y_list.append(0.40928)
        self.line_sourceC.end_y_list.append(0.58471)
        self.line_sourceC.end_y_list.append(0.76015)
        self.line_sourceC.end_y_list.append(0.9356)
        self.line_sourceC.setStatus(WidgetLINE.LINE_ENABLE)

        self.unit_fcc.setStyleSheet(com_style2)  # 常亮
        self.unit_sensor.setStyleSheet(com_style2)  # 常亮
        self.unit_datalink.setStyleSheet(com_style2)  # 常亮
        self.unit_actuator.setStyleSheet(com_style2)  # 常亮
        self.unit_gear.setStyleSheet(com_style2)  # 常亮
        # self.unit_parachute.setStyleSheet(com_style2) # 根据电源状态字判断
        self.unit_adc_heat.setStyleSheet(com_style2)  # 根据电源状态字判断
        # self.unit_pod.setStyleSheet(com_style2) # 根据电源状态字判断
        # self.unit_sc.setStyleSheet(com_style2) # 根据电源状态字判断
        # self.unit_vhf.setStyleSheet(com_style2) # 根据电源状态字判断
        self.unit_ads_b.setStyleSheet(com_style2)  # 常亮
        self.unit_dev_sensor.setStyleSheet(com_style2)  # 常亮
        self.unit_radar.setStyleSheet(com_style2)  # 常亮
        self.unit_emu.setStyleSheet(com_style2)  # 常亮
        self.unit_main_pump.setStyleSheet(com_style2)  # 根据电源状态字判断
        self.unit_aux_pump.setStyleSheet(com_style2)  # 根据电源状态字判断
        self.unit_flap_motor.setStyleSheet(com_style2)  # 根据电源状态字判断
        self.powerbusA.setStyleSheet(com_style2)  # 根据汇流条电流电压状态判断显示颜色
        self.powerbusB.setStyleSheet(com_style2)  # 根据汇流条电流电压状态判断显示颜色
        self.powerbusC.setStyleSheet(com_style2)  # 根据汇流条电流电压状态判断显示颜色
        self.power_battery.setStyleSheet(com_style2)  # 根据蓄电池电流电压判断显示颜色
        self.power_generator.setStyleSheet(com_style2)  # 根据发动机转速判断功率，根据蓄电池电流电压判断是否接通
        self.power_ground.setStyleSheet(com_style2)  # 根据电源状态字判断是否接通

    def getMouseLonLat(self, lon, lat):
        if lon < 0:
            lon_dir = 'W'
        else:
            lon_dir = 'E'
        lon = math.fabs(lon)
        lon_d = int(lon)
        lon_m = int((lon - lon_d) * 60)
        lon_s = int((lon - lon_d - lon_m / 60.0) * 3600)

        if lat < 0:
            lat_dir = 'S'
        else:
            lat_dir = 'N'
        lat = math.fabs(lat)
        lat_d = int(lat)
        lat_m = int((lat - lat_d) * 60)
        lat_s = int((lat - lat_d - lat_m / 60.0) * 3600)

        # tmp_str = "%c%03d°%02d′%02d″/%c%02d°%02d′%02d″" % (lon_dir, lon_d, lon_m, lon_s, lat_dir, lat_d, lat_m, lat_s)
        # self.readout_mouse_pos.setText(tmp_str)

    def servo_system_data_process(self, data):
        pass

    def fcc_system_data_process(self, data):
        control_mode = data["control_mode"]
        is_in_taxi_mode = control_mode["is_in_taxi_mode"]  # 当前是否处于滑行模式 1-滑行中 0-不处于滑行状态
        in_takeoff_mode = control_mode["in_takeoff_mode"]  # 起飞状态： 1：起飞（绿灯） 0：（灰色）
        in_land_mode = control_mode["in_land_mode"]  # 着陆状态： 1：着陆（绿灯） 0：（灰色）
        pre_nav = control_mode["pre_nav"]  # 预导航开关 1：预导航 0：未开启预导航
        on_air = control_mode["on_air"]  # 空地状态 1：空中（绿灯） 0：地面（红灯）
        on_taxi_correct = control_mode["on_taxi_correct"]  # 1：纠偏（绿灯）0：（红灯）

        # if pre_nav == 1:
        #     self.led_preNav.setStatus(WidgetLED.LED_ENABLE)
        # else:
        #     self.led_preNav.setStatus(WidgetLED.LED_DISABLE)
        # if on_taxi_correct == 1:
        #     self.led_taxi_correct.setStatus(WidgetLED.LED_ENABLE)
        # else:
        #     if is_in_taxi_mode == 1:
        #         self.led_taxi_correct.setStatus(WidgetLED.LED_WARNNING)
        #     else:
        #         self.led_taxi_correct.setStatus(WidgetLED.LED_DISABLE)
        # if in_takeoff_mode == 1:
        #     self.led_takeoff.setStatus(WidgetLED.LED_ENABLE)
        # else:
        #     self.led_takeoff.setStatus(WidgetLED.LED_DISABLE)
        #
        # if in_land_mode == 1:
        #     self.led_landing.setStatus(WidgetLED.LED_ENABLE)
        # else:
        #     self.led_landing.setStatus(WidgetLED.LED_DISABLE)

        if on_air == 1:
            self.led_on_air.setStatus(WidgetLED.LED_ENABLE)
        else:
            self.led_on_air.setStatus(WidgetLED.LED_DISABLE)

        route_flight = data["route_flight"]
        airline_number = route_flight["airline_number"]
        dot_number = route_flight["dot_number"]
        dx_m = route_flight["dx_m"]
        dy_m = route_flight["dy_m"]
        dh_m = route_flight["dh_m"]
        dpsi_deg = route_flight["dpsi_deg"]

        self.readout_airline_number.setText("%d" % airline_number)
        self.readout_airline_dot.setText("%d" % (dot_number + 1))
        self.readout_dtg_m.setText("%.1fm" % dx_m)
        self.readout_dy_m.setText("%.1fm" % dy_m)
        self.readout_dpsi_deg.setText("%.1f°" % dpsi_deg)

        # 将获取到的飞机位置更新到地图中
        sensor_fusion = data['sensor_fusion']
        lon_deg = sensor_fusion['lon_deg']
        lat_deg = sensor_fusion['lat_deg']
        heading_deg = sensor_fusion['heading_deg']
        self.map_widget.set_plane(lon_deg, lat_deg, heading_deg)

        # 计算当前位置距离跑道原点位置的距离和方位(发送预起飞指令之后才开始计算)
        if datahandler.origional_pos_inited:
            try:
                [ref_dist, ref_heading] = util_calc_ref_pos(lon_deg, lat_deg, datahandler.origional_lon,
                                                            datahandler.origional_lat)
            except Exception as e:
                logging.error(repr(e))
                ref_dist = 0
                ref_heading = 0
        else:
            ref_dist = 0
            ref_heading = 0
        self.readout_H_pos.setText("%dm/%d°" % (ref_dist, ref_heading))

        # 计算当前位置距离跑道尽头的距离（起飞、着陆或滑行时计算）调用此函数之前需先进行机场设置
        control_mode = data["control_mode"]
        is_in_taxi_mode = control_mode["is_in_taxi_mode"]  # 当前是否处于滑行模式 1-滑行中 0-不处于滑行状态
        in_takeoff_mode = control_mode["in_takeoff_mode"]  # 起飞状态： 1：起飞（绿灯） 0：（灰色）
        in_land_mode = control_mode["in_land_mode"]  # 着陆状态： 1：着陆（绿灯） 0：（灰色）

        if is_in_taxi_mode == 1 or in_takeoff_mode == 1 or in_land_mode == 1:
            tmp = cal_runway_distance(lon_deg, lat_deg, self.lon_deg_old, self.lat_deg_old)
            if tmp is not None:
                self.left_runway = tmp
        else:
            self.left_runway = 0
        self.readout_left_runway.setText("%dm" % self.left_runway)

        # 根据待飞距和速度信息计算距下一个航点的预计到达时间
        if on_air == 1 and in_takeoff_mode != 1 and in_land_mode != 1:
            vd_mps = sensor_fusion['vd_mps']
            if vd_mps > 0:
                eta_s = (dx_m + dy_m) / vd_mps
            else:
                eta_s = -1
        else:
            eta_s = -1

        self.readout_eta_s.setText("%ds" % eta_s)
        self.lon_deg_old = lon_deg
        self.lat_deg_old = lat_deg

    def sensor_mins_data_process(self, data):
        try:
            if data["mins_connect"] == 1:
                self.led_ins.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_ins.setStatus(WidgetLED.LED_WARNNING)
            self.readout_mins_freq.setText("%dHz" % data["freq"])

        except Exception as e:
            logging.error(e.args)
            logging.error(str(e))
            logging.error(repr(e))

    def sensor_bins_data_process(self, data):
        try:
            if data["bins_connect"] == 1:
                self.led_bins.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_bins.setStatus(WidgetLED.LED_WARNNING)
            self.readout_bins_freq.setText("%dHz" % data["freq"])

        except Exception as e:
            logging.error(e.args)
            logging.error(str(e))
            logging.error(repr(e))

    def sensor_adc_data_process(self, data):
        try:
            if data["adc_connect"] == 1:
                self.led_adc.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_adc.setStatus(WidgetLED.LED_WARNNING)
            self.readout_adc_freq.setText("%dHz" % data["freq"])

        except Exception as e:
            logging.error(e.args)
            logging.error(str(e))
            logging.error(repr(e))

    def sensor_radar_data_process(self, data):
        try:
            if data["radar1_connect"] == 1:
                self.led_radar1.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_radar1.setStatus(WidgetLED.LED_WARNNING)
            self.readout_radar1_freq.setText("%dHz" % data["radar0_freq"])

            if data["radar2_connect"] == 1:
                self.led_radar2.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_radar2.setStatus(WidgetLED.LED_WARNNING)
            self.readout_radar2_freq.setText("%dHz" % data["radar1_freq"])

            if data["radar3_connect"] == 1:
                self.led_radar3.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_radar3.setStatus(WidgetLED.LED_WARNNING)
            self.readout_radar3_freq.setText("%dHz" % data["radar2_freq"])

        except Exception as e:
            logging.error(repr(e))

    def sensor_gps_data_process(self, data):
        try:
            gps_connect = data['gps_connect']
            freq = data['freq']
            if gps_connect == 1:
                self.led_gps.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_gps.setStatus(WidgetLED.LED_WARNNING)

            self.readout_gps_freq.setText("%dHz" % freq)

        except Exception as e:
            logging.error(repr(e))

    def datalink_data_process(self, data):
        pass

    def elec_system_data_process(self, data):
        try:
            battery_cur = data["elec_cur_bat"]
            warnhandler.Cur_Bat.warn_level(battery_cur)

            elec_ground_power = data["elec_ground_power"]

            self.power_battery.setText("蓄电池\n%.1fA" % battery_cur)
            power_src = 0
            if battery_cur > 1:
                self.power_battery.setStyleSheet(com_style2)
                self.power_generator.setStyleSheet(com_style1)
                power_src = POINT_AT_BAT
            else:
                self.power_battery.setStyleSheet(com_style1)
                self.power_generator.setStyleSheet(com_style2)
                power_src = POINT_AT_GENERATOR

            if elec_ground_power == 1:
                self.power_ground.setStyleSheet(com_style2)
                power_src = POINT_AT_GROUND
            else:
                self.power_ground.setStyleSheet(com_style1)

            self.line_power_source.setStartPos(power_src)

            elec_volA = data["elec_volA"]
            warnhandler.Vol_A.warn_level(elec_volA)
            elec_curA = data["elec_curA"]
            warnhandler.Cur_A.warn_level(elec_curA)
            self.powerbusA.setText("汇流条A\n%.1fA/%.1fV" % (elec_curA, elec_volA))

            elec_volB = data["elec_volB"]
            warnhandler.Vol_B.warn_level(elec_volB)
            elec_curB = data["elec_curB"]
            warnhandler.Cur_B.warn_level(elec_curB)
            self.powerbusB.setText("汇流条B\n%.1fA/%.1fV" % (elec_curB, elec_volB))

            elec_volC = data["elec_volC"]
            warnhandler.Vol_C.warn_level(elec_volC)
            elec_curC = data["elec_curC"]
            warnhandler.Cur_C.warn_level(elec_curC)

            self.powerbusC.setText("14V汇流条\n%.1fA/%.1fV" % (elec_curC, elec_volC))

            elec_brake_power_on = data["elec_brake_power_on"]
            if elec_brake_power_on == 1:
                self.unit_gear.setStyleSheet(com_style2)
            else:
                self.unit_gear.setStyleSheet(com_style1)

            if data["elec_circuit_B_on"] == 1:
                self.unit_adc_heat.setStyleSheet(com_style2)
            else:
                self.unit_adc_heat.setStyleSheet(com_style1)

            # self.unit_main_pump.setStyleSheet(com_style2)
            # if data[""]==1:
            #     self.unit_main_pump.setStyleSheet(com_style2)
            # else:
            #     self.unit_main_pump.setStyleSheet(com_style1)
            if data["elec_aux_pump_on"] == 1:
                self.unit_aux_pump.setStyleSheet(com_style2)
                self.led_aux_fuel_pump.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.unit_aux_pump.setStyleSheet(com_style1)
                self.led_aux_fuel_pump.setStatus(WidgetLED.LED_WARNNING)

            self.unit_flap_motor.setStyleSheet(com_style2)

            if data["elec_connect"] == 1:
                self.led_elec.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_elec.setStatus(WidgetLED.LED_WARNNING)
            self.readout_pmu_freq.setText("%dHz" % data["elec_freq"])

        except Exception as e:
            logging.error(e.args)
            logging.error(str(e))
            logging.error(repr(e))

    def engine_system_data_process(self, data):
        try:
            press_fuel_psi = data["press_fuel_psi"]
            if press_fuel_psi > 4:  # 1号机主油泵是否上电通过油压反馈进行判断
                self.unit_main_pump.setStyleSheet(com_style2)
                self.led_fuel_pump.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.unit_main_pump.setStyleSheet(com_style1)
                self.led_fuel_pump.setStatus(WidgetLED.LED_WARNNING)
            # EMU LED灯状态更新
            if data["emu_connect"] == 1:
                self.led_emu.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_emu.setStatus(WidgetLED.LED_WARNNING)
            self.readout_emu_freq.setText("%dHz" % data["emu_freq"])

            status_switch = data["status_switch"]
            if status_switch == 0:
                self.led_switchA.setStatus(WidgetLED.LED_ENABLE)
                self.led_switchB.setStatus(WidgetLED.LED_ENABLE)
            elif status_switch == 0x01:
                self.led_switchA.setStatus(WidgetLED.LED_WARNNING)
                self.led_switchB.setStatus(WidgetLED.LED_ENABLE)
            elif status_switch == 0x10:
                self.led_switchA.setStatus(WidgetLED.LED_ENABLE)
                self.led_switchB.setStatus(WidgetLED.LED_WARNNING)
            elif status_switch == 0x11:
                self.led_switchA.setStatus(WidgetLED.LED_WARNNING)
                self.led_switchB.setStatus(WidgetLED.LED_WARNNING)
            else:
                self.led_switchA.setStatus(WidgetLED.LED_DISABLE)
                self.led_switchB.setStatus(WidgetLED.LED_DISABLE)

            lamp_boost = data["lamp_boost"]
            if lamp_boost == 0x00:
                self.led_TCU.setStatus(WidgetLED.LED_WARNNING)
            elif lamp_boost == 0xFF:
                self.led_TCU.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_TCU.setStatus(WidgetLED.LED_DISABLE)
            status_boost = data['status_boost']
            if status_boost == 0x00:
                self.led_TCU_servo.setStatus(WidgetLED.LED_WARNNING)
            elif status_boost == 0x01:
                self.led_TCU_servo.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_TCU_servo.setStatus(WidgetLED.LED_DISABLE)

            lamp_alarm = data['lamp_alarm']
            if lamp_alarm == 0x00:
                self.led_eng_warning.setStatus(WidgetLED.LED_WARNNING)
            elif lamp_alarm == 0xFF:
                self.led_eng_warning.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_eng_warning.setStatus(WidgetLED.LED_DISABLE)
            error = data['error']
            if error == 0xAA:
                self.led_eng_error.setStatus(WidgetLED.LED_WARNNING)
            elif error == 0x55:
                self.led_eng_error.setStatus(WidgetLED.LED_ENABLE)
            else:
                self.led_eng_error.setStatus(WidgetLED.LED_DISABLE)

        except Exception as e:
            logging.error(e.args)
            logging.error(str(e))
            logging.error(repr(e))

    def warnning_system_data_process(self, data):
        pass

    def command_echo_data_process(self, data):
        pass

    def equipment_data_process(self, data):
        pass

    def pre_send_data_process(self, data):
        pass

    def send_data_process(self, data):
        pass

    def request_echo_process(self, data):
        pass
    # def testinit(self):
    # self.led_TCU.setWindowIcon()
